<template>
  <view class="transfer-container">
    <up-navbar bgColor="#1db0fc" :title="useT('发薪/汇款')" autoBack leftIconColor="#fff" titleColor="#fff" placeholder />

    <view class="form-content">
      <!-- 可用余额 -->
      <view class="form-item">
        <text class="form-label">{{ useT('可用余额') }}</text>
        <text class="form-value">T{{ availableBalance }}</text>
      </view>

      <!-- 收款账户 -->
      <view class="form-item">
        <text class="form-label">{{ useT('收款账户') }}</text>
        <view class="input-group">
          <input class="form-input" type="text" :placeholder="useT('请填写钱包地址')" v-model="recipientAccount" @input="onAccountInput" />
          <button class="action-button icon-button" @click="pasteAddress">
            <text class="icon-text">📋</text>
          </button>
        </view>
      </view>

      <!-- 转出金额 -->
      <view class="form-item">
        <text class="form-label">{{ useT('转出金额') }}</text>
        <view class="input-group">
          <input class="form-input" type="digit" :placeholder="useT('请输入转出金额')" v-model="transferAmount" @input="onAmountInput" />
          <button class="action-button" @click="transferAll">
            <text class="action-text">{{ useT('全部转出') }}</text>
          </button>
        </view>
      </view>

      <!-- 收款人 -->
      <view class="form-item">
        <text class="form-label">{{ useT('收款人') }}</text>
        <input class="form-input" type="text" :placeholder="useT('请填写钱包地址后自动查询')" v-model="recipientName" disabled />
      </view>

      <!-- 转账备注 -->
      <view class="form-item">
        <text class="form-label">{{ useT('转账备注') }}</text>
        <input class="form-input" type="text" :placeholder="useT('请输入转账备注（可选）')" v-model="transferNote" />
      </view>

      <!-- 安全密码 -->
      <view class="form-item">
        <text class="form-label">{{ useT('安全密码') }}</text>
        <input class="form-input" type="password" :placeholder="useT('请输入安全密码')" v-model="securityPassword" />
      </view>
    </view>

    <!-- 提交按钮 -->
    <view class="submit-area">
      <button class="submit-button" @click="submitTransfer">
        <text class="submit-text">{{ useT('提交') }}</text>
      </button>
    </view>
  </view>
</template>

<script setup>
import { getUserBaseInfo, tradeMoney, updateUserInfo } from '@/api/user.js';
import { parsePaymentAddress } from '@/utils/crypto.js';
import { useT } from '@/utils/i18n.js';
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

// 响应式数据
const availableBalance = ref('0.00');
const transferAmount = ref('');
const recipientAccount = ref('');
const recipientName = ref('');
const securityPassword = ref('');
const transferNote = ref('');
const queryTimer = ref(null);

// 页面加载时获取可用余额
onLoad(() => {
  getAvailableBalance();
});

// 获取可用余额
const getAvailableBalance = async () => {
  try {
    const response = await updateUserInfo();
    console.log('用户信息API响应:', response);
    if (response.now_money) {
      // 使用 now_money 字段作为可用余额
      availableBalance.value = response.now_money || '0.00';
    }
  } catch (error) {
    console.error('获取可用余额失败:', error);
    uni.showToast({
      title: useT(error) || useT('获取余额信息失败'),
      icon: 'none',
      duration: 2000
    });
  }
};

// 转出数量输入
const onAmountInput = (e) => {
  let value = e.detail.value;

  // 只允许数字和一个小数点
  value = value.replace(/[^\d.]/g, '');

  // 确保只有一个小数点
  const parts = value.split('.');
  if (parts.length > 2) {
    value = `${parts[0]}.${parts.slice(1).join('')}`;
  }

  // 限制小数点后两位
  if (parts.length === 2 && parts[1].length > 2) {
    value = `${parts[0]}.${parts[1].substring(0, 2)}`;
  }

  transferAmount.value = value;
};

// 全部转出
const transferAll = () => {
  transferAmount.value = availableBalance.value;
};

// 收款账户输入
const onAccountInput = (e) => {
  recipientAccount.value = e.detail.value;

  // 清除之前的定时器
  if (queryTimer.value) {
    clearTimeout(queryTimer.value);
  }

  // 设置防抖，500ms后执行查询
  queryTimer.value = setTimeout(() => {
    queryRecipientInfo();
  }, 500);
};

// 粘贴地址
const pasteAddress = () => {
  uni.getClipboardData({
    success: (res) => {
      recipientAccount.value = res.data;

      // 清除之前的定时器
      if (queryTimer.value) {
        clearTimeout(queryTimer.value);
      }

      // 设置防抖，500ms后执行查询
      queryTimer.value = setTimeout(() => {
        queryRecipientInfo();
      }, 500);
    },
    fail: () => {
      uni.showToast({
        title: useT('粘贴失败'),
        icon: 'none'
      });
    }
  });
};

// 查询收款人信息
const queryRecipientInfo = async () => {
  if (!recipientAccount.value) {
    recipientName.value = '';
    return;
  }

  try {
    // 显示加载状态
    uni.showLoading({
      title: useT('查询中.')
    });

    // 使用crypto.js中的parsePaymentAddress函数解析钱包地址
    const parsedData = parsePaymentAddress(recipientAccount.value);
    console.log('解析后的数据:', parsedData);

    let uid;
    if (parsedData.valid) {
      // 有效的支付地址格式
      uid = parsedData.userId;
      if (parsedData.amount) {
        transferAmount.value = parsedData.amount;
      }
    } else {
      recipientAccount.value = '';
      // 尝试直接解析为uid（纯数字）
      throw new Error('钱包地址格式错误');
    }

    if (!uid) {
      throw new Error('钱包地址格式错误');
    }

    // 调用API获取用户信息
    const response = await getUserBaseInfo({ uid });
    console.log('用户信息API响应:', response);

    // 检查响应状态
    if (response.status === 200 && response.data) {
      recipientName.value = response.data.nickname || response.data.phone || `${useT('用户')}_${uid}`;
      uni.hideLoading();
    } else {
      throw new Error(response.msg || '获取用户信息失败');
    }
  } catch (error) {
    uni.hideLoading();
    console.error('查询收款人信息失败:', error);

    // 显示错误信息
    uni.showToast({
      title: useT(error.message) || error || useT('钱包地址格式错误或用户不存在'),
      icon: 'none',
      duration: 2000
    });

    recipientName.value = '';
  }
};

// 提交转账
const submitTransfer = () => {
  // 表单验证
  if (!transferAmount.value) {
    uni.showToast({
      title: useT('请输入转出金额'),
      icon: 'none'
    });
    return;
  }

  if (!recipientAccount.value) {
    uni.showToast({
      title: useT('请填写钱包地址'),
      icon: 'none'
    });
    return;
  }

  if (!securityPassword.value) {
    uni.showToast({
      title: useT('请输入安全密码'),
      icon: 'none'
    });
    return;
  }

  // 验证转出数量
  const amount = parseFloat(transferAmount.value);
  const available = parseFloat(availableBalance.value);

  if (amount <= 0) {
    uni.showToast({
      title: useT('转出金额必须大于0'),
      icon: 'none'
    });
    return;
  }

  if (amount > available) {
    uni.showToast({
      title: useT('转出金额不能超过可用余额'),
      icon: 'none'
    });
    return;
  }

  // 显示确认弹窗
  uni.showModal({
    title: useT('确认转账'),
    content: `${useT('确认向')} ${recipientName.value} ${useT('转账')} T${transferAmount.value}？`,
    cancelText: useT('取消'),
    confirmText: useT('确认'),
    success: (res) => {
      if (res.confirm) {
        processTransfer();
      }
    }
  });
};

// 处理转账
const processTransfer = async () => {
  try {
    uni.showLoading({
      title: useT('转账中.')
    });

    // 获取收款人uid
    let toUid;
    try {
      // 使用crypto.js中的parsePaymentAddress函数解析钱包地址
      const parsedData = parsePaymentAddress(recipientAccount.value);

      if (parsedData.valid) {
        // 有效的支付地址格式
        toUid = parsedData.userId;
      } else {
        // 尝试直接解析为uid（纯数字）
        if (/^\d+$/.test(recipientAccount.value)) {
          toUid = recipientAccount.value;
        } else {
          throw new Error('收款人信息解析失败');
        }
      }
    } catch {
      throw new Error('收款人信息解析失败');
    }

    // 准备转账参数
    const transferData = {
      number: transferAmount.value, // 转账数量
      to_uid: toUid, // 收款人用户ID
      mark: transferNote.value || useT('转账'), // 转账备注
      pwd: securityPassword.value, // 安全密码
      pwdtype: 1 // 安全密码类型
    };

    console.log('转账参数:', transferData);

    // 调用转账API
    const response = await tradeMoney(transferData);
    console.log('转账API响应:', response);

    // 检查响应状态
    if (response.status === 200) {
      uni.hideLoading();
      uni.showToast({
        title: useT('转账成功'),
        icon: 'success'
      });

      // 重新获取最新的可用余额
      await getAvailableBalance();

      // 清空表单
      transferAmount.value = '';
      recipientAccount.value = '';
      recipientName.value = '';
      securityPassword.value = '';
      transferNote.value = '';
    } else {
      throw new Error(response.msg || useT('转账失败'));
    }
  } catch (error) {
    uni.hideLoading();
    console.error('转账失败:', error);
    uni.showToast({
      title: error || useT('转账失败，请重试'),
      icon: 'none',
      duration: 3000
    });
  }
};
</script>

<style lang="scss" scoped>
.transfer-container {
  min-height: 100vh;
  background: #f5f5f5;
  padding: 20rpx;
}

.form-content {
  background: #ffffff;
  border-radius: 20rpx;
  padding: 40rpx;
  margin-bottom: 40rpx;
}

.form-item {
  margin-bottom: 40rpx;

  &:last-child {
    margin-bottom: 0;
  }
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333333;
  margin-bottom: 20rpx;
  font-weight: 500;
}

.form-value {
  display: block;
  font-size: 32rpx;
  color: #1db0fc;
  font-weight: 600;
}

.input-group {
  display: flex;
  align-items: center;

  .form-input {
    flex: 1;
    margin-right: 20rpx;
  }
}

.form-input {
  height: 80rpx;
  padding: 0 20rpx;
  border: 2rpx solid #e5e5e5;
  border-radius: 12rpx;
  font-size: 28rpx;
  color: #333333;
  background: #ffffff;

  &:focus {
    border-color: #1db0fc;
  }

  &::placeholder {
    color: #999999;
  }

  &:disabled {
    background: #f8f8f8;
    color: #999999;
  }
}

.action-button {
  height: 80rpx;
  padding: 0 30rpx;
  background: #1db0fc;
  border: none;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;

  &.icon-button {
    width: 80rpx;
    padding: 0;
  }
}

.action-text {
  color: #ffffff;
  font-size: 24rpx;
  font-weight: 500;
}

.icon-text {
  color: #ffffff;
  font-size: 32rpx;
}

.submit-area {
  padding: 0 20rpx;
}

.submit-button {
  width: 100%;
  height: 100rpx;
  background: #1db0fc;
  border: none;
  border-radius: 50rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 8rpx 24rpx rgba(18, 194, 132, 0.3);
}

.submit-text {
  color: #ffffff;
  font-size: 32rpx;
  font-weight: 600;
}
</style>
